<!-- eslint-disable no-undef -->
<!-- 采购管理-物料汇总列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <a-space style="margin-top: 20px" :size="30" direction="vertical" fill>
    <div>
      <a-space
        style="
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-right: 30px;
        "
      >
        <a-button type="primary" @click="create" :disabled="createEnable">
          <template #default>采购订单</template>
        </a-button>
        <a-button type="primary" @click="createTask" :disabled="createEnable">
          <template #default>采购任务</template>
        </a-button>
        <a-button
          type="primary"
          status="success"
          @click="createPlan"
          :disabled="createEnable"
        >
          <template #default>采购计划</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-table
        row-key="id"
        :data="matterData"
        :row-selection="rowSelection"
        v-model:selectedKeys="selectedKeys"
        :args="args"
        :pagination="false"
        :scroll="{ x: 1000 }"
        @select="onSelect"
        @select-all="onSelectAll"
      >
        <template #columns>
          <a-table-column>
            <template #title>序号 </template>
            <template #cell="{ rowIndex }">{{ rowIndex + 1 }}</template>
          </a-table-column>
          <a-table-column
            v-for="item in selectedHeader"
            :title="item.title"
            :data-index="item.code"
            :key="item.code"
            :ellipsis="true"
            :tooltip="{
              position: 'top',
            }"
          >
            <!-- 计划开始时间 -->
            <template v-if="item.code === 'apply_time'" #cell="{ record }">
              {{ dayjs(record.applyTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>

            <!-- 状态 -->
            <template v-else-if="item.code === 'state'" #cell="{ record }">
              <a-typography-text
                v-if="record.state === 1"
                style="color: #999999"
              >
                待处理
              </a-typography-text>
              <a-typography-text v-if="record.state === 2" type="primary">
                处理中
              </a-typography-text>
              <a-typography-text v-if="record.state === 3" type="success">
                已完成
              </a-typography-text>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="100">
            <template #title> 操作 </template>
            <template #cell="{ record }">
              <a-tooltip content="创建采购订单">
                <IconFont
                  type="icon-add-def"
                  :size="30"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="See(record)"
                />
              </a-tooltip>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-space>
  <AddOrder v-model:visible="modelVisible" :SeeDate="SeeDate" :type="setupType">
  </AddOrder>
  <addPlan v-model:visible="isPlanVisible" @addPlanProduct="addPlanProduct" />
  <AddTask
    v-model:visible="isTaskVisible"
    :tableData="taskTableData"
    v-if="taskTableData.length"
    ref="TaskRef"
  >
  </AddTask>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
  } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchaseProductList,
  } from '@/api/buy-management/buy-material/index';
  import { postPlanPurchase } from '@/api/buy-management/buy-plan/index';
  import { useBuyStore } from '@/store';
  import { cloneDeep } from 'lodash';

  import AddOrder from './add-order/index.vue';
  import addPlan from './add-plan/index.vue';

  let AddTask = defineAsyncComponent(() => import('./add-task/index.vue'));
  const store = useBuyStore();
  const isTaskVisible = ref(false);
  const route = useRoute();
  const router = useRouter();
  const title: string = '物料汇总列表';
  const breadCrumb: string[] = ['采购管理', '采购管理', '物料需求汇总列表'];
  const modelVisible = ref(false);
  const createEnable = ref(true);
  const setupType = ref();
  const isPlanVisible = ref(false);
  const taskTableData = ref([]);
  const data = ref<any>(store.collect);

  // 选择器配置
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页配置
  interface ParamsType {
    pageIndex: number;
    pageSize: number;
    number: string;
    clientCompanyName: string;
    status: number[];
    startTime: string;
    endTime: string;
  }
  const demandListParams = reactive<ParamsType>({
    pageIndex: 0,
    pageSize: 10,
    number: '',
    clientCompanyName: '',
    status: [],
    startTime: '',
    endTime: '',
  });
  const pageData = reactive({
    page: 0,
    size: 10,
  });

  const matterData = ref();

  const getData = () => {
    const tempSet = new Set();
    const afterData = {};

    data.value.forEach((item) => {
      if (!tempSet.has(item.name)) {
        const newItem = {
          ...item,
          chil: [],
          sid: `${item.id}`,
          applyNumber: `${item.applyNumber}`,
          sourceProductId: item.id,
        };
        afterData[item.name] = newItem;
        tempSet.add(item.name);
      } else {
        const currentItem = afterData[item.name];
        currentItem.sid += `,${item.id}`;
        currentItem.applyNumber += `,${item.applyNumber}`;
        currentItem.chil.push(JSON.parse(JSON.stringify(item)));
        currentItem.amount += item.amount;
        currentItem.sourceProductId = 0;
      }
    });
    const result = Object.values(afterData);
    matterData.value = result;
  };

  getData();
  // 数据条数改变时触发
  const pageSizeChange = (pageSize: number) => {
    demandListParams.pageSize = pageSize;
    getData();
  };
  //页码改变时触发
  const pageChange = (pageIndex: number) => {
    pageData.page = pageIndex > 1 ? pageIndex : 1;
    getData();
  };

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const columns = [
    {
      id: 2,
      title: '物料编码',
      visible: true,
      type: 'string',
      code: 'number',
    },
    {
      id: 3,
      title: '物料名称',
      visible: true,
      type: 'string',
      code: 'name',
    },
    {
      id: 4,
      title: '规格型号',
      visible: true,
      type: 'string',
      code: 'spec',
    },
    {
      id: 5,
      title: '基本单位',
      visible: true,
      type: 'string',
      code: 'basicName',
    },
    {
      id: 6,
      title: '需求数量',
      visible: true,
      type: 'string',
      code: 'amount',
    },

    {
      id: 7,
      title: '状态',
      visible: true,
      type: 'string',
      code: 'state',
    },
  ];
  const selectedHeader = computed(() => {
    return columns.filter((item) => item.visible);
  });

  const visible = ref(false);

  const detailsData = ref();
  const details = (Arr: any) => {
    visible.value = true;
    detailsData.value = Arr;
  };

  // 选择功能
  const SelectDate = ref([]);
  const onSelect = (e, keys, val: any) => {
    const index = SelectDate.value.findIndex((item) => {
      return item.id === keys;
    });
    if (index === -1) {
      SelectDate.value.push(val);
      createEnable.value = false;
    } else {
      SelectDate.value.splice(index, 1);
      if (SelectDate.value.length <= 0) {
        createEnable.value = true;
      }
    }
  };

  // 全选按钮
  const onSelectAll = (checked: boolean) => {
    if (checked) {
      // SelectDate.value = matterData.value;
      SelectDate.value = cloneDeep(matterData.value);
      createEnable.value = false;
    } else {
      SelectDate.value = [];
      createEnable.value = true;
    }
  };

  const SeeDate = ref();
  const See = (item: any) => {
    store.CreateOrder = {
      Product: [{ ...item }],
    };
    router.push({
      name: 'AddOrderPurchaseList',
    });
  };

  const SeeDateColumns = [
    {
      title: '物料编码',
      dataIndex: 'number',
    },
    {
      title: '物料名称',
      dataIndex: 'name',
    },
    {
      title: '型号规格',
      dataIndex: 'spec',
    },
    {
      title: '采购单位',
      dataIndex: 'spec',
    },
    {
      title: '需求数量',
      dataIndex: 'amount',
    },
    {
      title: '关联申请单号',
      dataIndex: 'email',
    },
    {
      title: '供应商名称',
      dataIndex: 'SupplierId',
    },
    {
      title: '产品指导单价',
      dataIndex: 'guidePrice',
    },
    {
      title: '折扣',
      dataIndex: 'discount',
    },
    {
      title: '合计',
      dataIndex: 'total',
    },
  ];

  const jump = () => {
    router.push({
      name: 'AddTaskPurchaseList',
    });
  };

  const create = () => {
    modelVisible.value = true;
    SeeDate.value = SelectDate.value;
    setupType.value = 2;
  };

  const createPlan = () => {
    isPlanVisible.value = true;
  };

  const addPlanProduct = async (number: string) => {
    await postPlanPurchase({ number, planProducts: SelectDate.value });
    router.push({
      name: 'PlanPurchaseList',
    });
  };

  const TaskRef = ref();
  const createTask = () => {
    taskTableData.value = SelectDate.value;
    isTaskVisible.value = true;
  };

  // let res = [];
</script>

<style scoped lang="less">
  // .content-head {
  // }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
    // font-size: 13px;
  }
</style>
